package org.itboys.core.service.mongo.web;

import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.service.lasted.SundayUploadService;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.core.common.ExceptionEnum;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.dto.scene.SundaySceneDto;
import org.itboys.core.entity.mongo.SundayGoods;
import org.itboys.core.entity.mongo.SundayGoodsSize;
import org.itboys.core.entity.mongo.SundayScene;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 作者：zzq
 * 时间：2018/10/11
 * 描述：场景
 */
@Service
public class SundaySceneService extends BaseMongoService<SundayScene> {
    @Resource(name = "mobileDs")
    private MongoDataSource sundayDataSource;
    @Autowired
    private SundayUploadService uploadService;
    @Autowired
    private SundayGoodsService goodsService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private SundayGoodsSizeService sizeService;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return sundayDataSource;
    }

    @Override
    protected Class<SundayScene> getEntityClass() {
        return SundayScene.class;
    }

    public PageResult<SundayScene> select(HttpServletRequest request) {
        Map<String, Object> param = ParamUtil.packageMongoExactParam(request, "");
        param.put("isDeleted", 0);
        Map<String, String> containsparam = ParamUtil.packageMongoVagueParam(request, "name");
        PageResult<SundayScene> result = super.containpageQuery(request, containsparam, param);
        return result;
    }

    /**
     * @param scene
     */
    public void save(SundayScene scene, MultipartFile imageFile, MultipartFile detailImageFile, MultipartFile[] rollImageFiles) throws IOException {
        Map<String, String> imageMap = uploadService.uploadSingle(imageFile);
        if (StringUtils.isNotEmpty(imageMap.get(uploadService.UPLOAD_HALF_PATH))) {
            scene.setImage(imageMap.get(uploadService.UPLOAD_HALF_PATH));
        }
        Map<String, String> detailImageMap = uploadService.uploadSingle(detailImageFile);
        if (StringUtils.isNotEmpty(detailImageMap.get(uploadService.UPLOAD_HALF_PATH))) {
            scene.setDetailImage(detailImageMap.get(uploadService.UPLOAD_HALF_PATH));
        }
        if (scene.getId() == 0L) {
            super.save(scene);
        } else {
            super.updateExceptEmpty(scene.getId(), scene);
        }
        if (rollImageFiles.length > 0) {
            //保存轮播图
            uploadService.uploadMultiWithRecord(rollImageFiles, scene.getId(), SundayScene.class.getSimpleName(), "场景" + scene.getId() + "的轮播图");
        }

    }

    /**
     * @param id
     * @return
     */
    public SundayScene findOne(Long id) {
        SundayScene scene = null;
        if (LongUtil.isNotZreo(id)) {
            scene = super.getById(id);
        } else {
            scene = new SundayScene();
            scene.setId(0l);
        }
        return scene;
    }


   /* public void releaseOld(Long sceneId, Double totalPrice) {
        SundayScene scene = super.getById(sceneId);
        if (scene.getStatus() != SundayCommonConstants.scene_status_dfb) {
            throw new ErrorException(ExceptionEnum.SCENE_STATUS_EXCEPTION.getValue());
        }
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("sceneId", scene.getId());
        Double goodsPrice = 0.00;
        List<SundayGoods> goodss = goodsService.list(param);
        if (ListUtil.isNotNull(goodss)) {
            for (SundayGoods goods : goodss) {
                goodsPrice += goods.getGoodsCostPrice() * goods.getNum();
            }
        } else {
            throw new ErrorException(ExceptionEnum.SCENE_GOODS_EXCEPTION.getValue());
        }
        //场景价格大于商品总价
        if (totalPrice > goodsPrice) {
            throw new ErrorException(ExceptionEnum.SCENE_PRICE_EXCEPTION.getValue());
        }
        Double ratio = totalPrice / goodsPrice;
        Double otherPrice = 0.0;
        //整理折扣价
        for (int i = 0; i < goodss.size(); i++) {
            SundayGoods goods = goodss.get(i);
            Double price = goods.getGoodsCostPrice();
            //最后一个商品
            if (i == goodss.size()) {
                Double endPrice = totalPrice - otherPrice;
                BigDecimal bg = new BigDecimal(endPrice / goods.getNum());
                endPrice = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                goods.setDiscountPrice(endPrice);
                //前面的商品
            } else {
                BigDecimal bg = new BigDecimal(price * ratio);
                price = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                goods.setDiscountPrice(price);
                otherPrice += price * goods.getNum();
            }
            goodsService.updateExceptEmpty(goods.getId(), goods);
        }
        scene.setPrice(totalPrice);
        scene.setStatus(SundayCommonConstants.scene_status_yfb);
        super.updateExceptEmpty(sceneId, scene);

    }*/

    /**
     * 发布
     *
     * @param sceneId
     */
    public void release(Long sceneId) {
        SundayScene scene = super.getById(sceneId);
        if (scene.getStatus() != SundayCommonConstants.scene_status_dfb) {
            throw new ErrorException(ExceptionEnum.SCENE_STATUS_EXCEPTION.getValue());
        }

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("sceneId", scene.getId());
        List<SundayGoods> goodss = goodsService.list(param);
        if (ListUtil.isNull(goodss)) {
            throw new ErrorException(ExceptionEnum.SCENE_GOODS_EXCEPTION.getValue());
        }
        List<Long> goodsIds = goodss.stream().map(e -> e.getId()).collect(Collectors.toList());
        if (ListUtil.isNull(goodss)) {
            throw new ErrorException(ExceptionEnum.SCENE_GOODS_EXCEPTION.getValue());
        }
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("sundayGoodsId in", goodsIds);
        List<SundayGoodsSize> sizes = sizeService.list(param);
        Double sceneMinPrice=0.0;
        Double sceneMaxPrice=0.0;
        for (SundayGoods goods :goodss) {
            Double goodsMinPrice=10000.0;
            Double goodsMaxPrice=0.0;
            for (SundayGoodsSize size : sizes) {
                if(goods.getId()==size.getSundayGoodsId().longValue()){
                    if(goodsMinPrice>size.getDiscountPrice()){
                        goodsMinPrice=size.getDiscountPrice();
                    }
                    if(goodsMaxPrice<size.getDiscountPrice()){
                        goodsMaxPrice=size.getDiscountPrice();
                    }
                }
            }
            sceneMinPrice+=goodsMinPrice*goods.getNum();
            sceneMaxPrice+=goodsMaxPrice*goods.getNum();
        }
        scene.setMaxPrice(sceneMaxPrice);
        scene.setMinPrice(sceneMinPrice);
        scene.setStatus(SundayCommonConstants.scene_status_yfb);
        super.updateExceptEmpty(sceneId, scene);
    }

    /**
     * 下架
     *
     * @param sceneId
     */
    public void downScene(Long sceneId) {
        SundayScene scene = super.getById(sceneId);
        if (scene.getStatus() != SundayCommonConstants.scene_status_yfb) {
            throw new ErrorException(ExceptionEnum.SCENE_STATUS_EXCEPTION.getValue());
        }
        scene.setStatus(SundayCommonConstants.scene_status_dfb);
        super.updateExceptEmpty(sceneId, scene);
    }

    /**
     * 组装多个
     *
     * @param scenes
     * @return
     */
    public List<SundaySceneDto> packageMultiDto(List<SundayScene> scenes) {
        List<SundaySceneDto> dtos = new ArrayList<>();
        for (SundayScene scene : scenes) {
            SundaySceneDto dto = new SundaySceneDto();
            BeanUtils.copyProperties(scene, dto);
            dto.setImage(resourceHolder.getStringValue("imgRoot") + scene.getImage());
            dtos.add(dto);
        }
        return dtos;
    }

    /**
     * 组装单个
     *
     * @param scene
     * @return
     */
    public SundaySceneDto packageSingleDto(SundayScene scene) {
        SundaySceneDto dto = new SundaySceneDto();
        BeanUtils.copyProperties(scene, dto);
        dto.setImage(resourceHolder.getStringValue("imgRoot") + scene.getImage());
        dto.setDetailImage(resourceHolder.getStringValue("imgRoot") + scene.getDetailImage());
        return dto;
    }


}
